/*
   This file will contain all the functions that have to do with sending messages
   to and from the FTP server
   */

#include "cli_net.h"


/*
   This function sends the message param
   to the server and returns the response of 
   the server

   It also checks to see if the recieved is the desired code,
   if not, then it returns a new message.
   */
RESP *sendAndReceive(char *message, int goodCode)
{
	char *msg;

	//if the message is null, just read from the server
	if(message != NULL)
	{
		//else write the message
		writeLine(&cmd_socket, message, strlen(message));
	}


	//read the response from the server
	if(!(msg = readLine(&cmd_socket)))
		return NULL;


	//copy the response into a temp buffer so it can be tokenized
	char tmp[strlen(msg) + 1];
	strcpy(tmp, msg);

	//get the code of the message
	int code = atoi(strtok(tmp, " "));
	

	RESP *r = newResp(code, msg);

	//if -1 is passed in, this means we don't want print errors (thread 0 will take care of this)
	if(goodCode != -1)
	{
		//check to see if its the right code
		if(isWrongCode(goodCode, r)) {
			freeResp(&r);
			return NULL;
		}


	}

	//return newly created server response
	return r;

}

void connectToCmd(char *hostname, char *port)
{
	if((cmd_socket = connectToServer(hostname, port)) < 0)
		return;

	int isLoggedIn = logInToServer();

	if (isLoggedIn) {
		printf("User Logged in!\n");
	}
	else
	{
		printf("Failed to log in\n");
		close(cmd_socket);
		cmd_socket = -1;
		exit(1);
	}

}

//this function enters passive mode
//will return true if successful, else false
bool enterPassiveMode(void)

{
	RESP *r;
	//loop counter
	int i;
	char ip[IP_LEN], port[PORT_LEN];  //will hold the port and ip address

	while(sendAndReceive(NULL, -1));
	if(!(r = sendAndReceive("PASV\r\n", C_PASV)))
		return false;

	//create temporary string for strtok
	char tmpStr[strlen(r->message) + 1];


	//used to point to return value of strtok
	char *tmpPtr;

	//copy the ftp message into the temp string
	strcpy(tmpStr, r->message);


	bzero(ip, IP_LEN);
	strtok(tmpStr, "(<");

	
	for(i = 0; i < 4; i++)
	{
		//get each byte of the ip address in ascii form
		tmpPtr = strtok(NULL, ",");
		
		//put buffer overflow check here
		
		strcat(ip, tmpPtr);
		strcat(ip, ".");
	}

	
	//remove the final dot from the ip address
	ip[strlen(ip) - 1] = '\0';

	//buffer overflow check for port here

	//now get the port to connect to...
	int portInt = atoi(strtok(NULL, ","));

	//the first part o f the port must be multiplied by 256
	portInt *= 256;

	//now add the second part of the port to first part
	portInt += atoi(strtok(NULL, ","));

	//convert the port to a string
	sprintf(port, "%d", portInt); 

	if((data_socket = connectToServer(ip, port)) == -1)
		return false;

	return true;

}

bool isWrongCode(int code, RESP *r)
{
	if(r->code != code)
	{
		printf("%s", r->message);
		fflush(stdout);
		return true;
	}
	else
		return false;

}
